package com.spa.interfaces.common;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spa.application.command.douyin.CreateOrderCommand;
import com.spa.application.command.douyin.LoginCommand;
import com.spa.domain.service.DouYinOauthService;
import com.spa.infrastructure.common.ResponseMessage;
import com.spa.infrastructure.repository.po.DouYinCommentPO;
import com.spa.infrastructure.repository.service.DouYinCommentRepositoryService;
import com.spa.infrastructure.service.douyin.DouYinGoodLifeService;
import com.spa.infrastructure.service.douyin.DouYinMiNiService;
import com.spa.infrastructure.service.douyin.DouYinWebService;
import com.spa.infrastructure.service.douyin.param.NotifyParam;
import com.spa.infrastructure.service.douyin.param.webhook.EventEnum;
import com.spa.infrastructure.service.douyin.param.webhook.WebHookParam;
import com.spa.infrastructure.service.douyin.result.*;
import com.spa.infrastructure.service.douyin.result.webhook.VerifyWebHookResult;
import com.spa.interfaces.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@RestController
@RequestMapping("dy")
@Slf4j
public class DouYinController extends BaseController {

    @Autowired
    private DouYinGoodLifeService douYinGoodLifeService;

    @Autowired
    private DouYinMiNiService douYinMiNiService;

    @Autowired
    private DouYinWebService douYinWebService;

    @Autowired
    private DouYinOauthService douYinOauthService;

    @Autowired
    public ObjectMapper mapper;

    @Autowired
    private DouYinCommentRepositoryService douYinCommentRepositoryService;
    @PostMapping("getOpenId")
    @SaIgnore
    public ResponseMessage<JsCode2SessionResult> miniGetOpenId(@Validated @RequestBody LoginCommand command){
        JsCode2SessionResult jsCode2SessionResult = douYinMiNiService.login(command.getCode(), command.getAnonymousCode());
        return responseHelper.success(jsCode2SessionResult);
    }

    @PostMapping("createOrder")
    @SaIgnore
    public ResponseMessage<CreateOrderResult> createOrder(@Validated @RequestBody CreateOrderCommand command){
        CreateOrderResult createOrderResult = douYinMiNiService.createOrder(command.getOrderCode());
        return responseHelper.success(createOrderResult);
    }

    @PostMapping("notify/bytedancePay")
    @SaIgnore
    public ResponseMessage<DouYinResult> notify(@RequestBody NotifyParam param){
        log.info("NotifyParam : {}", param);
        DouYinResult result = DouYinResult.builder()
                .err_no(0)
                .err_tips("success")
                .build();
        return responseHelper.success(result);
    }

    @PostMapping("queryShop")
    @SaIgnore
    public ResponseMessage<ShopPoiQueryResult> queryShop() throws JsonProcessingException {
        ShopPoiQueryResult shopPoiQueryResult = douYinGoodLifeService.queryShop();
        return responseHelper.success(shopPoiQueryResult);
    }

    @PostMapping("verify")
    @SaIgnore
    public ResponseMessage<VerifyResult> verify(String code, String poiId) throws JsonProcessingException {
        PrepareResult prepareResult = douYinGoodLifeService.prepareByCode(code);
        VerifyResult verifyResult = douYinGoodLifeService.verify(prepareResult, poiId);
        return responseHelper.success(verifyResult);
    }

    @PostMapping("cancel")
    @SaIgnore
    public ResponseMessage<CancelResult> cancel(String verifyId, String certificateId) throws JsonProcessingException {
        CancelResult cancelResult = douYinGoodLifeService.cancel(verifyId, certificateId);
        return responseHelper.success(cancelResult);
    }

    @PostMapping("get")
    @SaIgnore
    public ResponseMessage<String> get(String code) throws JsonProcessingException {
        PrepareResult prepareResult = douYinGoodLifeService.prepareByCode(code);
        List<String> codes = prepareResult.getData().getCertificates().stream().map(PrepareResult.Certificate::getEncrypted_code).toList();
        String response = "";
        if (CollectionUtil.isNotEmpty(codes)) {
            response = douYinGoodLifeService.get(codes.get(0));
        }
        return responseHelper.success(response);
    }

    @GetMapping("notify/oauth/connect")
    @SaIgnore
    public void notify4Oauth(@RequestParam String code) throws NoSuchPaddingException {
        log.info("code : {}", code);
        try {
            douYinWebService.addOrUpdateAccount(code);
        } catch (JsonProcessingException | InvalidAlgorithmParameterException | IllegalBlockSizeException |
                 NoSuchAlgorithmException | BadPaddingException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("webhook")
    @SaIgnore
    public Object webhook(@RequestBody WebHookParam param) throws JsonProcessingException {
        log.info("webhook {}", param);
        if (EventEnum.verify_webhook.getEventName().equals(param.getEvent())) {
            return mapper.readValue(mapper.writeValueAsString(param.getContent()), VerifyWebHookResult.class);
        } else if (EventEnum.item_comment_reply.getEventName().equals(param.getEvent())) {
            JSONObject jsonObject = JSONUtil.parseObj(param.getContent());
            log.info("content : {}", jsonObject.get("comment_id"));
            DouYinCommentPO po = new DouYinCommentPO();
            po.setFromUserId(param.getFrom_user_id());
            po.setToUserId(param.getTo_user_id());
            po.setClientKey(param.getClient_key());
            po.setCommentId(String.valueOf(jsonObject.get("comment_id")));
            po.setCommentUserId(String.valueOf(jsonObject.get("comment_user_id")));
            po.setContent(String.valueOf(jsonObject.get("content")));
            po.setCreateTime((Integer) jsonObject.get("create_time"));
            po.setDiggCount((Integer) jsonObject.get("digg_count"));
            po.setReplyCommentTotal((Integer) jsonObject.get("reply_comment_total"));
            po.setReplyToCommentId(String.valueOf(jsonObject.get("reply_to_comment_id")));
            po.setReplyToItemId(String.valueOf(jsonObject.get("reply_to_item_id")));
            po.setAtUserId(String.valueOf(jsonObject.get("at_user_id")));
            po.setAvatar(String.valueOf(jsonObject.get("avatar")));
            po.setNickName(String.valueOf(jsonObject.get("nick_name")));
            po.setParentId(String.valueOf(jsonObject.get("parent_id")));
            douYinCommentRepositoryService.addDouYinComment(po);
        }
        return "success";
    }

    @PostMapping("getIframeByItemId")
    @SaIgnore
    public ResponseMessage<String> getIframeByItemId(String itemId) throws JsonProcessingException {
        String res = douYinWebService.getIframeByItemId(itemId);
        log.info("{}", res);
        return responseHelper.success(res);
    }

}




